//
//  XQActionSheet.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/6.
//

import UIKit

class XQActionSheet: XQBaseActionSheetControl {
    
    typealias ResultCallback = (_ index: Int , _ title: String?) -> Void
    
    fileprivate var resultCallback : ResultCallback?
        
    fileprivate var items:[XQActionSheetItem] = [XQActionSheetItem]() {
        didSet {
            tableView.reloadData()
        }
    }
    
    fileprivate var headView:UIView?
        
    fileprivate lazy var tableView: UITableView = {
        let table = UITableView()
        table.register(XQActionSheetCell.self, forCellReuseIdentifier: "XQActionSheetCell")
        table.delegate = self
        table.dataSource = self
        table.showsHorizontalScrollIndicator = false
        table.showsVerticalScrollIndicator = false
        table.backgroundColor = UIColor.white
        table.tableHeaderView = headView
        table.bounces = false
        table.separatorStyle = .none
        return table
    }()
    
   fileprivate override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    fileprivate convenience init(titles:[String],headView:UIView? = nil) {
        self.init(frame: UIScreen.main.bounds)
        self.headView = headView
        self.items = createDefautItem(titles: titles)
        setupView()
    }
    
    class func actionSheet(titles:[String],headView:UIView?) -> XQActionSheet {
        let action = XQActionSheet.init(titles: titles, headView: headView)
        return action
    }
    
    fileprivate func setupView() {
        addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.bottom.trailing.leading.equalTo(self)
            make.height.equalTo(getTableViewHeight())
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func show(callback:(ResultCallback?)) {
        resultCallback = callback
        
        var window: UIWindow! = UIApplication.shared.delegate?.window as? UIWindow
        if window == nil {
            window = UIApplication.shared.currentWindow
        }
        
        if window.isKind(of: UIWindow.self) {
            window.addSubview(self)
            self.snp.makeConstraints { (make) in
                make.edges.equalTo(window)
            }
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
        if tableView.isHidden {
            tableView.isHidden = false
        }
        
        let trans = transAni(type: CATransitionType.moveIn, subType: CATransitionSubtype.fromTop, function: CAMediaTimingFunctionName.easeOut)
        
        tableView.layer.add(trans, forKey: nil)
    }
    
    @objc func dissmiss(animation:Bool) {
        if animation {
            let trans = transAni(type: CATransitionType.push, subType: CATransitionSubtype.fromBottom, function: CAMediaTimingFunctionName.linear)
            trans.delegate = self
            tableView.layer.add(trans, forKey: nil)
            
            let ani = opacityReduceAnimation(time:0.4)
            self.layer.add(ani, forKey: nil)
        } else {
            removeFromSuperview()
        }
        tableView.isHidden = true
    }
    
    override func clickBg() {
        super.clickBg()
        dissmiss(animation: true)
        resultCallback?(-1, "什么都没选择,点击了空白处")
    }
}

extension XQActionSheet {
    
    fileprivate func createDefautItem(titles:[String]) -> [XQActionSheetItem]{
        let itemTitles = titles
        var itemArr = [XQActionSheetItem]()
        for (index,title) in itemTitles.enumerated() {
            var lineHeight:Float = 1.0
            if index == itemTitles.count - 2 {
                lineHeight = 5.0
            } else {
                if index == itemTitles.count - 1 {
                    lineHeight = 0.0
                } else {
                    lineHeight = 1
                }
            }
            let actionItem = XQActionSheetItem.init(title: title, titleFont: UIFont.init(name: "PingFangSC-Regular", size: 17) ?? UIFont.systemFont(ofSize: 17), titleColor: UIColor.black, height: 55, bottomLineHeight: lineHeight)
            itemArr.append(actionItem)
            
        }
        
        return itemArr
    }
    
    func getTableViewHeight() -> Float {
        var height:Float = 0.0
        
        for item in self.items {
            height = height + item.height + item.bottomLineHeight
        }
        height += Float(headView?.frame.height ?? 0)
        
        return height
    }
}

extension XQActionSheet : CAAnimationDelegate{
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if flag {
            removeFromSuperview()
        }
    }
}

extension XQActionSheet : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let  cellIndex = tableView.dequeueReusableCell(withIdentifier: "XQActionSheetCell", for: indexPath)
        if let cell = cellIndex as? XQActionSheetCell {
            if indexPath.row >= 0 && indexPath.row < items.count {
                cell.cellInfo = items[indexPath.row]
                cell.selectionStyle = .none
                if indexPath.row == items.count - 1 {
                    cell.separatorInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
                } else {
                    cell.separatorInset = UIEdgeInsets.zero
                }
            }
            return cell
        }
        return cellIndex
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row < items.count && indexPath.row >= 0 {
            let item = items[indexPath.row]
            return CGFloat(item.height + item.bottomLineHeight)
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        guard let head = headView else { return 0.0 }
        return head.frame.height
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let cell = tableView.cellForRow(at: indexPath)
        
        if let cel = cell as? XQActionSheetCell {
            resultCallback?(indexPath.row,cel.cellInfo.title)
        }
        dissmiss(animation: true)
        tableView.deselectRow(at: indexPath, animated: false)
    }

}
